package com.owc.controller.admin;

import com.owc.common.custom.annotation.Advice;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.enums.FileTypeEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.common.oss.OssUtils;
import com.owc.common.tool.FileUtils;
import com.owc.common.tool.UtilsService;
import com.owc.domain.BaseResult;
import com.owc.domain.entity.OssResult;
import com.owc.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * @Author xiaom
 * @Date 2020/3/2 16:07
 * @Version 1.0.0
 * @Description <>
 **/
@RestController
@RequestMapping(value = "/admin/upload")
@Api(tags = "(manage-V2)文件上传")
@Slf4j
public class UploadController {

    private final UploadService uploadService;

    public UploadController(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    @PostMapping(value = "/image",consumes ={MediaType.MULTIPART_FORM_DATA_VALUE})
    @ApiOperation("上传图片")
    @ApiImplicitParam(name = "fileType",value = "文件类型 10(图片) 20(文件) 30(可执行文件)")
    public BaseResult<OssResult> uploadImage(@RequestParam("file") MultipartFile file,
                                             @RequestParam @NotNull(message = "请选择文件类型") Integer fileType) throws IOException, FileUploadException {
        if(file.isEmpty() || fileType == null){
            throw new BadRequestException(ExceptionEnum.UPLOAD_ERR);
        }
        Optional<FileTypeEnum> optional = FileTypeEnum.match(fileType);
        if(!optional.isPresent()){
            throw new BadRequestException("请选择文件类型");
        }
        return BaseResult.success(uploadService.upload(file,optional.get()));
    }
}
